/*
 * Copyright (C) 2011 SANSOU SYSTEMS Co., Ltd. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package jp.co.sansou.android.atnd.activity;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jp.co.sansou.android.asynctask.AsyncTaskProgressDialog;
import jp.co.sansou.android.asynctask.IAsyncTaskCallBack;
import jp.co.sansou.android.asynctask.IAsyncTaskDoInBackground;
import jp.co.sansou.android.atnd.R;
import jp.co.sansou.android.atnd.beans.AtndEventBean;
import jp.co.sansou.android.atnd.common.OrgAlertDialog;
import jp.co.sansou.android.atnd.common.Util;
import jp.co.sansou.android.atnd.db.AtndDao;
import jp.co.sansou.android.atnd.util.AtndEventSearch;
import jp.co.sansou.android.atnd.util.JsonObj4List;

import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ActAtndSearch extends Activity {

	/** キーワード（AND） */
	private EditText edtKeyword;

	/** 検索結果表示用ListView */
	private ListView lvwResult;

	/** 検索結果保持リスト */
	private List<AtndEventBean> listResult;

	/** 登録済みリスト */
	private List<Integer> listEntriedEventId;

	/** 検索ボタン */
	private Button btnSearch;

	/** 登録ボタン */
	private Button btnReg;

	private IAsyncTaskDoInBackground asyncTaskDoInBackground = new IAsyncTaskDoInBackground() {
		@Override
		public void doInBackground() {
			AtndEventSearch.Builder builder = new AtndEventSearch.Builder();

			// キーワード（AND）
			String keyword = edtKeyword.getText().toString();
			if (!StringUtils.isEmpty(keyword)) {
				builder.keyword(Util.splitSpace(keyword));
			}

			AtndEventSearch atndEventSearch = builder.build();

			JSONObject json = atndEventSearch.searchEventResultJson();

			try {
				listResult = JsonObj4List.getEventList(json);
				if (listResult != null && listResult.size() > 0) {
					AtndDao dao = new AtndDao(ActAtndSearch.this);
					listEntriedEventId = dao.getEntriedEventIds(listResult);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
	};

	private IAsyncTaskCallBack asyncTaskCallBack = new IAsyncTaskCallBack() {
		@Override
		public void doInBackgroundCallBack() {
			lvwResult.setAdapter(new OrgListAdapter(ActAtndSearch.this,
					listResult));
		}
	};

	/**
	 * <pre>
	 * 検索ボタン用OnClickListenerです。
	 * AsyncTaskによりProgressDialogを表示し、画面で指定された検索条件に基づいて
	 * 検索処理を行います。
	 * また、検索した結果を画面に表示します。
	 * </pre>
	 */
	private View.OnClickListener lsnrSearch = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			searchAtndInfo();
			btnReg.setEnabled(false);
		}
	};

	private View.OnClickListener lsnrReg = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			regAtndInfo();
		}
	};

	private AdapterView.OnItemClickListener lsnrListView = new AdapterView.OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapterview, View view, int i,
				long l) {
			AtndEventBean bean = listResult.get(i);

			Intent intent = new Intent(ActAtndSearch.this, ActAtndDetail.class);

			intent.putExtra(
					AtndEventSearch.AtndEventJsonSubKeys.EVENT_ID.name(),
					bean.getEventId());
			intent.putExtra(AtndEventSearch.AtndEventJsonSubKeys.TITLE.name(),
					bean.getTitle());
			intent.putExtra(
					AtndEventSearch.AtndEventJsonSubKeys.STARTED_AT.name(),
					bean.getStartedAt());
			intent.putExtra(
					AtndEventSearch.AtndEventJsonSubKeys.ENDED_AT.name(),
					bean.getEndedAt());
			intent.putExtra(AtndEventSearch.AtndEventJsonSubKeys.LIMIT.name(),
					bean.getLimit());
			intent.putExtra(AtndEventSearch.AtndEventJsonSubKeys.PLACE.name(),
					bean.getPlace());
			intent.putExtra(AtndEventSearch.AtndEventJsonSubKeys.URL.name(),
					bean.getUrl());
			intent.putExtra(
					AtndEventSearch.AtndEventJsonSubKeys.OWNER_NICKNAME.name(),
					bean.getOwnerNickname());
			intent.putExtra(
					AtndEventSearch.AtndEventJsonSubKeys.DESCRIPTION.name(),
					bean.getDescription());

			startActivity(intent);
		}
	};

	private TextView.OnEditorActionListener lsnrEditorAction = new TextView.OnEditorActionListener() {

		@Override
		public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
			if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
				searchAtndInfo();
			}
			return false;
		}

	};

	public void setListAdapter(List<AtndEventBean> list) {
		OrgListAdapter adapter = new OrgListAdapter(this, list);
		lvwResult.setAdapter(adapter);
	}

	private void searchAtndInfo() {
		AsyncTaskProgressDialog asyncTaskProgressDialog = new AsyncTaskProgressDialog(
				ActAtndSearch.this, getResources().getString(
						R.string.msg_progress_wait), asyncTaskDoInBackground,
				asyncTaskCallBack);

		asyncTaskProgressDialog.execute();

		InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(btnSearch.getWindowToken(),
				0);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.atnd_search);

		// 画面コントロールの取得
		edtKeyword = (EditText) findViewById(R.id.edt_keyword);
		btnSearch = (Button) findViewById(R.id.btn_search);
		btnReg = (Button) findViewById(R.id.btn_reg);
		lvwResult = (ListView) findViewById(R.id.lvw_result);

		// イベントリスナーの登録
		btnSearch.setOnClickListener(lsnrSearch);
		btnReg.setOnClickListener(lsnrReg);
		lvwResult.setOnItemClickListener(lsnrListView);
		edtKeyword.setOnEditorActionListener(lsnrEditorAction);

		btnReg.setEnabled(false);
	}

	@SuppressWarnings("unchecked")
	private void regAtndInfo() {
		// チェックボックスにチェックがない場合はメッセージを出力して終了
		List<AtndEventBean> regList = getCheckedList();
		if (regList.size() == 0) {
			OrgAlertDialog.showWarnDialog(this,
					getResources().getString(R.string.msg_warn_001), null);
			return;
		}

		AtndDao dao = new AtndDao(this);
		boolean result = dao.regAtndInfo(regList
				.toArray(new AtndEventBean[regList.size()]));

		if (result) {
			for (AtndEventBean regBean : regList) {
				listEntriedEventId.add(regBean.getEventId());
			}
			((ArrayAdapter<AtndEventBean>) lvwResult.getAdapter())
					.notifyDataSetChanged();
		} else {
			Toast.makeText(this, "登録に失敗！？", Toast.LENGTH_LONG);
		}
	}

	/**
	 * ListView内のチェックボックスにチェックが付いている件数を返します。
	 * 
	 * @return チェックが付いている件数
	 */
	private List<AtndEventBean> getCheckedList() {
		List<AtndEventBean> list = new ArrayList<AtndEventBean>();
		for (AtndEventBean bean : listResult) {
			if (bean.isSelected()) {
				list.add(bean);
			}
		}
		return list;
	}

	/**
	 * ATND検索結果のリストに設定する独自Adapterクラスです。
	 * 
	 * @author SANSOU SYSTEMS Co.
	 */
	class OrgListAdapter extends ArrayAdapter<AtndEventBean> {
		private LayoutInflater mInflater;

		public OrgListAdapter(Context context, List<AtndEventBean> listDaily) {
			super(context, 0, listDaily);
			mInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {

			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.atnd_event_list_row,
						null);
			}
			AtndEventBean item = this.getItem(position);

			if (item != null) {
				TextView tvwTitle = (TextView) convertView
						.findViewById(R.id.tvw_title);
				TextView tvwAccept = (TextView) convertView
						.findViewById(R.id.tvw_accept);
				TextView tvwYmd = (TextView) convertView
						.findViewById(R.id.tvw_ymd);
				TextView tvwWaiting = (TextView) convertView
						.findViewById(R.id.tvw_waiting);

				tvwTitle.setText(item.getTitle());
				tvwAccept.setText(item.getAccepted() + "／" + item.getLimit());
				tvwWaiting.setText(String.valueOf(item.getWaiting()));

				Date startedAt = Util.formatDateIso8601(item.getStartedAt());
				if (startedAt != null) {
					tvwYmd.setText(Util.dateToStr(startedAt));
				}
			}

			CheckBox chbSelect = (CheckBox) convertView
					.findViewById(R.id.chb_select);
			ImageView imvSumi = (ImageView) convertView
					.findViewById(R.id.imv_sumi);
			chbSelect.setVisibility(View.VISIBLE);
			imvSumi.setVisibility(View.GONE);
			if (listEntriedEventId != null && listEntriedEventId.size() > 0) {
				if (listEntriedEventId.contains(item.getEventId())) {
					chbSelect.setVisibility(View.GONE);
					imvSumi.setVisibility(View.VISIBLE);
				}
			}

			chbSelect.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(CompoundButton buttonView,
						boolean isChecked) {
					listResult.get(position).setSelected(isChecked);
					boolean checkedFlg = false;
					for (AtndEventBean bean : listResult) {
						if (bean.isSelected()) {
							checkedFlg = true;
							break;
						}
					}
					btnReg.setEnabled(checkedFlg);
				}
			});
			chbSelect.setChecked(listResult.get(position).isSelected());

			return convertView;
		}
	}
}
